//
//  VC12Operation.swift
//  ChapterAll
//
//  Created by Kevin on 2020/5/7.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VC12Operation: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        test5()
    }
    
    func test5() -> Void {
        let op1 = BlockOperation {
            print("1,\(Thread.current)")
        }
        let op2 = BlockOperation {
            print("2,\(Thread.current)")
        }
        let op3 = BlockOperation {
            print("3,\(Thread.current)")
        }
        op1.addDependency(op2)
        op2.addDependency(op3)
        
        let queue = OperationQueue()
        queue.addOperation(op1)
        queue.addOperation(op2)
        queue.addOperation(op3)
    }
    
    func test4() -> Void {
        let operation = OperationQueue()
        operation.maxConcurrentOperationCount = 2
        operation.addOperation {
            print("1,\(Thread.current)")
        }
        operation.addOperation {
            print("2,\(Thread.current)")
        }
        operation.addOperation {
            sleep(4)
            print("3,\(Thread.current)")
        }
        
        operation.waitUntilAllOperationsAreFinished()
        
        print("4,\(Thread.current)")
    }
    
    func test3() -> Void {
        let operation = OperationQueue()
        operation.maxConcurrentOperationCount = 2
        operation.addOperation {
            print("1,\(Thread.current)")
        }
        operation.addOperation {
            print("2,\(Thread.current)")
        }
        operation.addOperation {
            print("3,\(Thread.current)")
        }
    }
    
    func test2() -> Void {
        let operation = OperationQueue.main
        operation.addOperation {
            print("1,\(Thread.current)")
        }
        operation.addOperation {
            print("2,\(Thread.current)")
        }
        operation.addOperation {
            print("3,\(Thread.current)")
        }
    }
    
    func test1() -> Void {
        let operation = BlockOperation()
        operation.addExecutionBlock {
            print("1,\(Thread.current)")
        }
        operation.addExecutionBlock {
            print("2,\(Thread.current)")
        }
        operation.addExecutionBlock {
            print("3,\(Thread.current)")
        }
        operation.start()
    }
}
